// pages/productDetails/forward/forward.js
var http = require('../../../utils/server.js')
var util = require('../../../utils/util.js')
Page({
  data: {
    topActive: 0,
    topMenuData: [{
      title: "转发客户",
      img: "/images/deta_ico_cli_nor.png",
      activeImg: "/images/deta_ico_cli_sel.png"
    }, {
      title: "超级海报",
      img: "/images/deta_ico_pos_nor.png",
      activeImg: "/images/deta_ico_pos_sel.png"
    }],
    imgs: [{
      src: '',
      cover: false
    }],
    selectIndex: 0,
    step: 0,
    qrcodeImg: '',
    isCompletedDraw: false
  },

  onLoad: function(option) {
    var that = this
    var userInfo = wx.getStorageSync('userInfo');
    that.setData({
      product_id: option.product_id,
      shop_id: option.shop_id || userInfo.shopId
    })

    http.post({
      url: "product/getPosters",
      product_id: that.data.product_id
    }, function(data) {
      console.log('getPosters', data)
      var imgs = [];
      for (i in data['imgs']) {
        var img = {
          src: data['imgs'][i],
          cover: false
        }
        imgs.push(img)
      }
      that.setData({
        name: data.name,
        imgs: imgs
      })
    })
  },
  topMenuTap(e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      topActive: index
    })
  },
  select(e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      selectIndex: index
    })
  },
  nextStep(e) {
    var that = this
    var index = e.currentTarget.dataset.index
    //生成超级海报
    if (index == 2) {
      var img = this.data.imgs[this.data.selectIndex].src
      http.post({
        url: "weixin/qrcode",
        product_id: this.data.product_id,
        shop_id: this.data.shop_id,
        img: img
      }, function(data) {
        console.log('qrcode', data)
        that.data.isCompletedDraw = true
        that.setData({
          qrcodeImg: data + '?' + Math.random() / 9999
        })
      })

    }

    this.setData({
      step: index
    })

  },
  setStep(e) {
    var step = e.currentTarget.dataset.step
    this.setData({
      step: step
    })
  },
  add: function() {
    var that = this
    // if (that.data.imgs.length > 9) {
    // util.showModal("最多只能上传10张") 
    //   return false;
    // }
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: function(res) {
        var tempFilePaths = res.tempFilePaths
        var imgs = that.data.imgs
        imgs.unshift({
          src: tempFilePaths[0],
          cover: true
        })
        that.setData({
          imgs: imgs
        })

        var token = wx.getStorageSync('token') || "";
        console.log(token)
        const uploadTask = wx.uploadFile({
          url: 'https://www.ymqvip.com/api/upload/uploadPic',
          filePath: tempFilePaths[0],
          name: 'imgfile',
          formData: {
            'token': token,
            'posters': 1
          },
          success: function(res) {
            var uploadData = JSON.parse(res.data)
            if (uploadData.code == 0) {
              console.log('上传成功', )
              var imgs = that.data.imgs
              imgs[0].hideCover = true
              imgs[0].src = uploadData.data
              that.setData({
                imgs: imgs
              })
              setTimeout(function() {
                var imgs = that.data.imgs
                imgs[0].cover = false
                that.setData({
                  imgs: imgs
                })
              }, 1000)
            } else {
              util.showModal("上传出错，" + res.message)
              return false;
            }
          },
          fail: function(e) {
            console.log('上传出错', e)
            util.showModal("上传出错，请联系管理员。")
            return false;
          }
        })

        uploadTask.onProgressUpdate((res) => {
          console.log('上传进度', res.progress)
          // console.log('已经上传的数据长度', res.totalBytesSent)
          // console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)         
        })

      }
    })
  },
  //转发
  onShareAppMessage: function(ops) {
    if (ops.from === 'button') {
      console.log(ops.target)
    }
    return {
      title: this.data.name ? this.data.name : '羽毛球VIP',
      path: 'pages/productDetails/productDetails?product_id=' + this.data.product_id +'&shop_id='+this.data.shop_id,
      imageUrl: this.data.imgs[this.data.selectIndex].src,
      success: function(res) {
        console.log("转发成功:" + JSON.stringify(res));
      },
      fail: function(res) {
        console.log("转发失败:" + JSON.stringify(res));
      }
    }

  },

  //点击分享朋友圈
  sharepyq: function(e) {

    var that = this;
    if (!that.data.isCompletedDraw) {
      wx.showToast({
        title: '图片正在生成中…',
      });
      return;
    }

    util.showBusy('努力加载中…')
    wx.downloadFile({
      url: that.data.qrcodeImg,
      success: function(result) {
        that.data.preurl = result.tempFilePath
        
        //生产环境时 记得这里要加入获取相册授权的代码
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.writePhotosAlbum']) { //未授权，则重新授权
              wx.authorize({
                scope: 'scope.writePhotosAlbum',
                success() {
                  // 用户已经同意小程序使用保存相册功能，
                  wx.saveImageToPhotosAlbum({
                    filePath: that.data.preurl,
                    success(res) {
                      util.hideToast()  
                      util.showModal('图片已保存到相册，赶紧晒一下吧~')
                    }
                  });
                },
                fail: function(res) {
                  console.log("拒绝授权");
                  console.log(res);
                  that.setData({
                    modaltwo: false,
                    auth: false
                  });
                }
              })
            } else { //已经授权，则保存图片
              wx.saveImageToPhotosAlbum({
                filePath: that.data.preurl,
                success(res) {
                  util.showModal('图片已保存到相册，赶紧晒一下吧~')
                }
              });
            }
          }
        });
      },
      fail: function(res) {
        console.log("保存失败")
      }
    })
  }

})